package cn.wolfcode.crm.web.filter;

import cn.wolfcode.crm.util.JSONResult;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.IOException;

//重写authc的拦截规则
public class MyFormFilter extends FormAuthenticationFilter{

    //登陆成功规则
    protected boolean onLoginSuccess(AuthenticationToken token, Subject subject,
                                     ServletRequest request, ServletResponse response) throws Exception {
        //把JSON字符串输出到浏览器上
        JSONResult result = new JSONResult();
        response.getWriter().print(new ObjectMapper().writeValueAsString(result));

        //不需要执行后面的过滤器 或者是Controller的方法
        // 因为配置文件已经配置了 登陆成功跳转到其他的界面
        return false;
    }

    //登陆失败规则
    protected boolean onLoginFailure(AuthenticationToken token, AuthenticationException e,
                                     ServletRequest request, ServletResponse response) {
        String errorMsg = "其他异常,请联系管理员";
        //判断属于哪种异常 响应不同异常的错误信息显示给用户
        if(e instanceof UnknownAccountException){
            errorMsg = "用户名不存在!";
        }else if (e instanceof IncorrectCredentialsException){
            errorMsg = "密码错误!";
        }
        //响应JSON格式回去
        JSONResult result = new JSONResult();
        try {
            response.getWriter().print(new ObjectMapper().
                    writeValueAsString(result.remark(errorMsg)));
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        return false;
    }
}
